package com.hongshan.wallet.core.wallet

import android.app.Application
import android.databinding.ObservableField
import com.hongshan.wallet.Constant
import com.hongshan.wallet.base.MyViewModel
import com.hongshan.wallet.base.SingleLiveEvent
import com.hongshan.wallet.http.HttpClient
import com.hongshan.wallet.tryRun
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener
import com.scwang.smartrefresh.layout.listener.OnRefreshListener
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.async
import kotlinx.coroutines.launch

/**
 * Copyright Zhangxx.
 * Copyright (c) 2019
 * All rights reserved
 *
 * @project  : Wallet
 * @package  : com.example.wallet.core.home
 * @author   : zhangxx
 * @date     : 2019/3/28
 * @email    : qq957413212@hotmail.com
 * @desc     : //TODO
 */
class CommissionPagerViewModel(application: Application, val type: Int,val typeDetails:Int?) : MyViewModel(application) {

    var startTime: Long? = null
    var endTime: Long? = null

    val adapter = CommissionRecycleAdapter(arrayListOf())

    val loadEnable = ObservableField(true)
    val refreshEnable = ObservableField(true)

    val loadingComplete = SingleLiveEvent<Unit>()

    val onRefresh = OnRefreshListener {
        refresh(1, Constant.OTHER_CONFIG.ROWS, startTime, endTime)
    }

    val onLoad = OnLoadMoreListener {
        refresh(adapter.list.size / Constant.OTHER_CONFIG.ROWS + 1, Constant.OTHER_CONFIG.ROWS, startTime, endTime)
    }

    fun refresh(
        pages: Int,
        number: Int,
        startTime: Long?,
        endTime: Long?
    ) {
        this.startTime = startTime
        this.endTime = endTime
        GlobalScope.launch(Dispatchers.Main) {
            val result = GlobalScope.async(Dispatchers.IO) {
                tryRun {
                    HttpClient.httpApi.getMoneyRecord(type, typeDetails, pages, number, startTime, endTime).execute()
                }
            }
            val body = result.await()?.body()
            loadingComplete.call()
            if (body?.code == 0) {
                if (pages == 1){
                    adapter.list.clear()
                }
                adapter.list.addAll(body.data.list)
                adapter.notifyDataSetChanged()
                if (body.data.list.size < Constant.OTHER_CONFIG.ROWS) {
                    loadEnable.set(false)
                } else {
                    loadEnable.set(true)
                }
            }
        }
    }


}